﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Nirvana
{

    public sealed class NetSendBody
    {
        //缓存最大数量
        private const int maxcount = 8;
        private static Stack<NetSendBody> serialstack = new Stack<NetSendBody>();
        private MemoryStream memorystream;
        /// <summary>
        /// 包体大小：多少个字节
        /// </summary>
        private uint size;

        private int offset;
        public int Offset { get { return offset; } set { offset = value; } }


        private object callback;
        public object CallBack { get { return callback; } set { callback = value; } }
        public uint GetSize()
        {
            return this.size;
        }

        public byte[] GetBytes()
        {
            if (memorystream == null) return null;
            return memorystream.GetBuffer();
        }

        public int GetLength()
        {
            if (this.memorystream == null)
            {
                return 0;
            }
            return (int)this.memorystream.Length;
        }

        public static NetSendBody PopSerial()
        {
            if (serialstack.Count > 0)
            {
                return serialstack.Pop();
            }
            return new NetSendBody();
        }

        public static void PushSerial(NetSendBody data)
        {
            if (serialstack.Count < maxcount)
            {
                data.size = 0;
                data.offset = 0;
                data.CallBack = null;
                serialstack.Push(data);
            }
        }

        public void WriteStream(byte[] bytes)
        {
            if (this.memorystream == null)
            {
                this.memorystream = new MemoryStream(4 + bytes.Length);
            }
            else
            {
                this.memorystream.Seek(0, SeekOrigin.Begin);
                this.memorystream.SetLength(0);
            }
            //前4个字节保存包体长度
            uint len = (uint)bytes.Length;
            var buffer = new byte[]
            {
                (byte)(len & 255u),
                (byte)(len>> 8 & 255u),
                (byte)(len>> 16 & 255u),
                (byte)(len>> 24 & 255u)
            };
            this.memorystream.Write(buffer, 0, 4);//先写入包体总长度
            this.memorystream.Write(bytes, 0, bytes.Length);//再写入包体数据
            this.size = len;
        }

    }
}